package cn.com.fattiger.framework.remoting.netty4.server.handle;

import io.netty.channel.Channel;

import java.util.concurrent.Executor;

import cn.com.fattiger.framework.remoting.netty4.common.Invocation;
import cn.com.fattiger.framework.remoting.netty4.common.protocol.handle.AbstractReceivedHandle;
import cn.com.fattiger.framework.remoting.netty4.common.protocol.handle.SendHandle;
import cn.com.fattiger.framework.remoting.netty4.processor.LoginProcessor;
import cn.com.fattiger.framework.remoting.processor.IProcessor;

public class ServerReceivedHandle extends AbstractReceivedHandle<Channel> {

	private final SendHandle sendHandle;
	private final Executor executor;

	public ServerReceivedHandle(SendHandle sendHandle, Executor executor) {
		this.sendHandle = sendHandle;
		this.executor = executor;
	}

	@Override
	public void receivedObject(Channel channel, Object obj) {
		// TODO Auto-generated method stub

		System.out.println("request:" + obj);
		// if (OBJ instanceOf RequestParams) {
		if (obj instanceof Invocation) {
			Invocation request = (Invocation) obj;
			executor.execute(new HandlerRunnable(channel, request));
		}
	}

	class HandlerRunnable implements Runnable {
		private Channel channel;
		private Invocation request;

		public HandlerRunnable(Channel channel, Invocation request) {
			this.channel = channel;
			this.request = request;
		}

		public void run() {
			Invocation response = new Invocation(request.getUuid());

			IProcessor a = new LoginProcessor();
			Object result = a.process(request);
			response.setResponse(request.getRequest() + ":" + result);
			System.out.println("send to client:" + response);
			this.writeRespond(channel, response);
		}

		private void writeRespond(Channel channel, Invocation response) {
			sendHandle.send(channel, response);
		}

	}

}